package io.github.consoles.dsa;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by yiihua-013 on 17/1/21.
 *
 * 背包数据结构:此处实现采用了链表
 */
public class Bag<Item> implements Iterable<Item> {

    /**
     * helper linked list
     */
    private class Node{
        private Item item;
        private Node next;
    }

    private int size; // elements length
    private Node first; // beginning of the bag

    public Bag() {
        first = null;
        size = 0;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int size(){
        return size;
    }

    public void add(Item item){
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        size++;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {

        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}
